package com.vinaprime.primeschedule.presentation;

import java.text.ParseException;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.SearchView.OnCloseListener;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.vinaprime.primeschedule.businesslayer.VPContact_BL;
import com.vinaprime.primeschedule.entities.VPContact;
//import android.R;

public class VPContactActivity extends Activity {
//	private SimpleCursorAdapter adapter;
	
	public final static String CONTACT_ID = "com.vinaprime.primeschedule.presentation.MESSAGE";
	
	int _idConntact;
	int _position;
	
	List<VPContact> listContact;
	List<VPContact> listContactFilter;
    ListView listView;
    ListViewContactAdapter list_adapter;
    VPContact_BL contactBL;
    ApplicationInformation appInfo;
    String path;
    SearchView mSearchView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_vpcontact);
		ActionBar actionBar = getActionBar();
		Drawable d=getResources().getDrawable(R.drawable.background_top_shape_green);  
		actionBar.setBackgroundDrawable(d);
	

    	actionBar.setCustomView(R.layout.activity_filter_search_view);
		actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);
    	SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		mSearchView = (SearchView) findViewById(R.id.searchViewFilter);
		
		mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
		mSearchView.setIconifiedByDefault(true);
		
		mSearchView.setOnQueryTextListener(new OnQueryTextListener() {
			
			@Override
			public boolean onQueryTextSubmit(String query) {
				// TODO Auto-generated method stub
				//listContactFilter.filterData(query);
				//expandAll();
				
				return false;
			}
			
			@Override
			public boolean onQueryTextChange(String newText) {
				// TODO Auto-generated method stub
				//Toast.makeText(getApplicationContext(), newText, Toast.LENGTH_SHORT).show();
				showListItemFilter(newText);
				return false;
			}
		});
		
		mSearchView.setOnCloseListener(new OnCloseListener() {
			
			@Override
			public boolean onClose() {
				// TODO Auto-generated method stub
				//listContactFilter.filterData("");
				//expandAll();
				
				return false;
			}
		});
	
	
		//------------------------------------------------//
		appInfo = new ApplicationInformation(this);
		path = appInfo.getDBPath();
		contactBL = new VPContact_BL(this,  path + "databases/");
		//showSearchView();
		showListItem();
		
	}
	public void showSearchView(){
		//Create Menu Search
        ActionBar myActionBar = getActionBar();
    	myActionBar.setCustomView(R.layout.activity_filter_search_view);
    	
		
		
	};
	public void showListItem()
	{	 
		try {
			listContact = contactBL.getAllContact();
			
			listView = (ListView) findViewById(R.id.listView_Contact);
			list_adapter = new  ListViewContactAdapter(listContact,this);
			listView.setAdapter(list_adapter);
			//Toast.makeText(getBaseContext(),  "  111", Toast.LENGTH_SHORT).show();
			
			
			listView.setOnItemClickListener(new OnItemClickListener() {
				@SuppressWarnings("static-access")
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {					
				//Toast.makeText(getBaseContext(),  "  222", Toast.LENGTH_SHORT).show();
					listView.setSelector(R.drawable.list_selector_pressed_shape);
					listView.setFocusable(true);
					if( !String.valueOf(listContact.get(position).getVpcID()).isEmpty()){
						_idConntact = listContact.get(position).getVpcID();
						_position = position;
						Intent intent = new Intent(getApplicationContext(), VPContactActivityDetail.class);
					//intent.putExtra(CONTACT_ID, String.valueOf(listContact.get(arg2).getVpcID()));
					intent.putExtra(CONTACT_ID, new String[]{"VIEW", String.valueOf(_idConntact)});
					startActivityForResult(intent, 5);
					}
					
				}
				
			});
			listView.setOnItemLongClickListener(new OnItemLongClickListener() {

				@SuppressWarnings("static-access")
				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					
					listView.setSelector(R.drawable.list_selector_pressed);
					listView.setFocusable(true);
					//listView.setBackgroundResource(R.drawable.list_selector_pressed);
					_idConntact = listContact.get(arg2).getVpcID();
					_position = arg2;
					registerForContextMenu(listView);
					return false;
				}
			});
			
			
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		} 
		catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//Toast.makeText(getBaseContext(), e.toString() + "  aaa", Toast.LENGTH_SHORT).show();
		}
		

		

	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			 ContextMenuInfo menuInfo) {
			 // TODO Auto-generated method stub
			 super.onCreateContextMenu(menu, v, menuInfo);
			 getMenuInflater()
			 .inflate(R.menu.vpcontact_context, menu);
			 menu.setHeaderTitle(R.string.ctx_action_title);			
			 }
	 @Override
	 public boolean onContextItemSelected(MenuItem item) {
			 switch(item.getItemId())
			 {
			 case R.id.ctx_Edit:
					Intent intent = new Intent(getApplicationContext(), VPContactActivityDetail.class);
					//intent.putExtra(CONTACT_ID, String.valueOf(listContact.get(arg2).getVpcID()));
					intent.putExtra(CONTACT_ID, new String[]{"EDIT", String.valueOf(_idConntact)});
					startActivityForResult(intent, 5);
			 break;
			 case R.id.ctx_Delete:				   
				 contactBL.deleteContactbyID(_idConntact);
			//	 Intent intent_refetch = new Intent(getApplicationContext(), VPContactActivity.class);					
				//	startActivity(intent_refetch);
				 listContact.remove(_position);
				 list_adapter = new  ListViewContactAdapter(listContact,this);
				   list_adapter.notifyDataSetChanged();
				   listView.setAdapter(list_adapter);
				   listView.invalidateViews();
			 break;			
			 }
			 return super.onContextItemSelected(item);
	 }
	 
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.vpcontact, menu);
		return true;
	}	
	
	public void show_detailcontact(View view) {
    
    	Intent intent = new Intent(getApplicationContext(), VPContactActivityDetail.class);
		//intent.putExtra(CONTACT_ID, valueOf("NO_ID").toString());
    	//String ABC = "ADD";
    	intent.putExtra(CONTACT_ID,new String []{"EDIT",String.valueOf(_idConntact)});
    	startActivity(intent);

	
}

	
	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.action_add:
	      //Toast.makeText(this, "Menu Add selected", Toast.LENGTH_SHORT).show();
	      //Add new contact
	    	Intent intent = new Intent(getApplicationContext(), VPContactActivityDetail.class);
			intent.putExtra(CONTACT_ID,new String []{"ADD","NO_ID"});
			startActivityForResult(intent, 5);
	    	//End
	      break;
	    
	    default:
	    	break;
	    }

	    return true;
	  } 
	
	
	public void showListItemFilter(String _contains)
	{		
		try {
			listContactFilter = contactBL.getContactInContains(_contains,listContact);
			
			listView = (ListView) findViewById(R.id.listView_Contact);
			list_adapter = new  ListViewContactAdapter(listContactFilter,this);
			listView.setAdapter(list_adapter);
			
			listView.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long arg3) {					
				//Toast.makeText(getBaseContext(),  "  222", Toast.LENGTH_SHORT).show();
					if( !String.valueOf(listContactFilter.get(position).getVpcID()).isEmpty()){
						_idConntact = listContactFilter.get(position).getVpcID();
						_position = position;
						Intent intent = new Intent(getApplicationContext(), VPContactActivityDetail.class);
					//intent.putExtra(CONTACT_ID, String.valueOf(listContact.get(arg2).getVpcID()));
					intent.putExtra(CONTACT_ID, new String[]{"VIEW", String.valueOf(_idConntact)});
					startActivity(intent);
					}
					
				}
				
			});
			listView.setOnItemLongClickListener(new OnItemLongClickListener() {

				@Override
				public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
						int arg2, long arg3) {
					_idConntact = listContactFilter.get(arg2).getVpcID();
					_position = arg2;
					registerForContextMenu(listView);
					return false;
				}
			});
			
			
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			
		} 
		
		catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			//Toast.makeText(getBaseContext(), e.toString() + "  aaa", Toast.LENGTH_SHORT).show();
		}
		
			
	}
	
	private class ListViewContactAdapter extends BaseAdapter {
		 

	    Context context;
	    List<VPContact> listContact;
	    public ListViewContactAdapter(List<VPContact> _listContact,Context _context) {
	    	listContact = _listContact;
	        context=_context;
	    }
	    @Override
	    public int getCount() {
	 
	        return listContact.size();
	    }

	    @Override
	    public Object getItem(int position) {
	        // TODO Auto-generated method stub
	       return listContact.get(position);
	    }
	 
	    @Override
	    public long getItemId(int position) {
	        // TODO Auto-generated method stub
	    	return listContact.get(position).getVpcID();
	    	 
	    }
	 
	    @Override
	    public View getView(int position, View convertView, ViewGroup parent) {
	 
	        // create a new LayoutInflater
	        LayoutInflater inflater = (LayoutInflater) context
	                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	 
	        View listView;
	        listView = null;
	        convertView = null;// avoids recycling of grid view
	        byte [] imagebyte = null;
	        if (convertView == null) {
	 
	        	listView = new View(context);
	            // inflating list view item
	        	listView = inflater.inflate(R.layout.activity_vpcontact_sub, null);
	        	
	        	//Tao VPContact
	        	VPContact _vpContact = new VPContact();
	        	_vpContact = (VPContact)getItem(position);
	        	//set value into textview id
	        	
	            TextView textViewId = (TextView) listView.findViewById(R.id.textView_ID);
	            textViewId.setText(String.valueOf(_vpContact.getVpcID()));
	            
	            // set value into textview
	            TextView textView = (TextView) listView.findViewById(R.id.textView_Ho);
	            textView.setText(_vpContact.getVpcLastName()+" "+_vpContact.getVpcFistName());
	            // set value into textview email
	            TextView textViewEmail = (TextView) listView.findViewById(R.id.textView_Email);
	            textViewEmail.setText(_vpContact.getVpcEmail());
	            // set value into ImageView
	            ImageView imgView = (ImageView)listView.findViewById(R.id.image_Contact);       
	            if (_vpContact.getVpcImage()!= null) {
	            	imagebyte = _vpContact.getVpcImage();
	            	imgView.setImageBitmap(BitmapFactory.decodeByteArray(imagebyte, 0, imagebyte.length));
				} else {
		           
		            imgView.setImageResource(R.raw.user1);
				}
	            			
	        }
	 
	        return listView;
	    }

	    
	}
}

